//
//  WebSocketService.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/6.
//

import Combine
import ComposableArchitecture
import CoreLocation
import Foundation
import Logging
import MapKit
import SwiftUI
import UserNotifications

class WebSocketService: ObservableObject {
    static let shared = WebSocketService()
    private var wsManager : WebSocketManager = WebSocketManager()
    
    let logger = Logger(label: "websocket")
    let vm = ViewModel.shared
//        private lazy var urlSession: URLSession = {
//            let config = URLSessionConfiguration.default
//            config.waitsForConnectivity = true    // 允许网络恢复后自动重试
//            config.timeoutIntervalForResource = 60 * 60  // 资源超时1小时
//            return URLSession(configuration: config)
//        }()
//    private var webSocketTask: URLSessionWebSocketTask?
    
//    let didChange = PassthroughSubject<Void, Never>()
    
    @Published var orderState: EnumCurrentState = .none
    
//    private var reconnectTimer: Timer?             // 重连定时器
//    private var isReconnecting = false             // 防止重复重连
    
//    var stateResult: OrderState = .none {
//        didSet {
//            didChange.send()
//        }
//    }
    
    var opened = false
    
    var appInBackground = false
    
    
    
    public var baseUrl = URL(string: "wss://www.zhuiso.cn/wss/jcy/websocket/chat")
    
    private init() {
//        connect()  // 初始化时启动连接
    }
    
    func initWebSocketManager(){

        // 设置回调
        wsManager.onConnected = {
            print("🎉 WebSocket连接成功，发送测试消息")
            self.sendJoinMessage()
            
            
        }

        wsManager.onDisconnected = { error in
            if let error = error {
                print("😢 WebSocket断开连接: \(error.localizedDescription)")
            } else {
                print("😐 WebSocket正常断开")
            }
        }

        wsManager.onMessageReceived = { str in
            print("📨 收到消息: \(str)")
            let logger = Logger(label: "websocket")
            do{
                let decoder = JSONDecoder()
                let contentBase = try decoder.decode(APIResponse.self, from: Data(str.utf8))
                
                if (contentBase.cmd == "MESSAGE") {
                    print("[socket message] MESSAGE")
                    let contentMessage = try decoder.decode(WebSocketMessageBaseResult.self, from: Data(str.utf8))
                    let openId = ViewModel.shared.passenger.openId
                    if contentMessage.type == "text" {
                        print("[socket message] MESSAGE text")
                        let contentMessageText = try decoder.decode(WebSocketMessageTextResult.self, from: Data(str.utf8))
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            for m in contentMessageText.contents {
                                if m.type == "text" {
                                    var textContent  = contentMessageText.content
                                    if  let shortMessageCode = contentMessageText.phraseCode  {
                                        if !shortMessageCode.isEmpty && shortMessageCode != "null" {
                                            print("[Socket] [Message] [Phrase] code: \(shortMessageCode)")
                                            textContent = self.vm.getShortMessageContent(code: shortMessageCode)
                                        }
                                    }
                                    
                                    let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageText.from, name: "司机", openId: contentMessageText.from!, type: .Driver), text: textContent, type: .text, voice: nil, video: nil, url: nil, phraseCode: "")
                                    logger.info("[socket message] text:\(message)")
                                    
                                    if contentMessageText.from != openId { // 自己发的消息
                                        logger.info("[socket message] text append to array :\(message)")
                                        CarOrder.shared.messages.append(message)
                                        print("=--------====----------\(message)")
                                        self.sendLocalNotification(message: contentMessageText.content!)
                                    }
                                    
                                }
                            }
                            CarOrder.shared.save()
                            print("[socket message] messages :\(CarOrder.shared.messages.count) ")
                            if CarOrder.shared.messages.count > 0 && !ViewModel.shared.inChat {
                                print("[socket message] send .newMessage notice.")
                                let notice = Notification(name: .newMessage, object: nil, userInfo: nil)
                                NotificationCenter.default.post(notice)
                                
                            }
                        }
                    } else if contentMessage.type == "image" {
                        let contentMessageImage = try decoder.decode(WebSocketMessageMediaResult.self, from: Data(str.utf8))
                        
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            for m in contentMessageImage.contents {
                                if m.type == "image" {
                                    let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageImage.from, name: "司机", openId: contentMessageImage.from!, type: .Driver), text: nil, type: .image, voice: nil, video: nil, url: m.url, phraseCode: "")
                                    //if !self!.appInBackground {
                                    if contentMessageImage.from != openId { // 自己发的消息
                                        logger.info("[socket message] image:\(message)")
                                        CarOrder.shared.messages.append(message)
                                        self.sendLocalNotification(message: NSLocalizedString("收到一条图片消息", comment: "Received a picture message"))
                                    }
                                }
                            }
                            if contentMessageImage.from != openId { // 自己发的消息
                                CarOrder.shared.save()
                            }
                            print("[socket message] messages :\(CarOrder.shared.messages.count) ")
                            if CarOrder.shared.messages.count > 0 && !ViewModel.shared.inChat {
                                print("[socket message] send .newMessage notice.")
                                let notice = Notification(name: .newMessage, object: nil, userInfo: nil)
                                NotificationCenter.default.post(notice)
                                
                            }
                        }
                    } else if contentMessage.type == "voice" {
                        let contentMessageImage = try decoder.decode(WebSocketMessageMediaResult.self, from: Data(str.utf8))
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            for m in contentMessageImage.contents {
                                if m.type == "voice" {
                                    let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageImage.from, name: "司机", openId: contentMessageImage.from!, type: .Driver), text: nil, type: .voice, voice: nil, video: nil, url: m.url, phraseCode: "")
                                    if contentMessageImage.from != openId { // 自己发的消息
                                        logger.info("[socket message] voice:\(message)")
                                        CarOrder.shared.messages.append(message)
                                        //}
                                        self.sendLocalNotification(message: NSLocalizedString("收到一条声音消息", comment: "Received a voice message"))
                                    }
                                }
                            }
                            if contentMessageImage.from != openId { // 自己发的消息
                                CarOrder.shared.save()
                            }
                            print("[socket message] messages :\(CarOrder.shared.messages.count) ")
                            if CarOrder.shared.messages.count > 0 && !ViewModel.shared.inChat {
                                print("[socket message] send .newMessage notice.")
                                let notice = Notification(name: .newMessage, object: nil, userInfo: nil)
                                NotificationCenter.default.post(notice)
                                
                            }
                        }
                    }
                }else{
                    let content = try decoder.decode(CMDResponse.self, from: Data(str.utf8))
                    if content.cmd == "CMD", content.subCmd == "LAOS_JIEDAN" { // 接单
                        let content2 = try decoder.decode(WebSocketJiedanResult.self, from: Data(str.utf8))
                        
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            CarOrder.shared.driverId = content2.peopleId!
                            CarOrder.shared.carNo = (content2.driver?.chepai)!
                            CarOrder.shared.driverPhone = (content2.driver?.laosPhone)!
                            if let headavitor = (content2.driver?.headavitor) {
                                CarOrder.shared.headavitor =  headavitor
                            }
                            let p = CLLocationCoordinate2D(latitude: (content2.driver?.carLat!)!, longitude: (content2.driver?.carLon!)!)
                            
                            CarOrder.shared.startTime = Date().secondsSince1970
                            CarOrder.shared.carPosition = p
                            
                            logger.info("websockets jiedan received:\(content2)")
                            
                            self.orderState = .waiting
                            
                            self.sendLocalNotification(message: NSLocalizedString("司机已接单", comment: "The driver has accepted the ride."))
                            
                            MapConfig.shared.annotationItems.removeAll()
                            let annoItem = MapAnnotationModel(coordinate: p, car: CarInfo(id: CarOrder.shared.driverId, carNo: CarOrder.shared.carNo, driverMobile: CarOrder.shared.driverPhone, direction: 0, speed: 0, status: .busy))
                            MapConfig.shared.annotationItems.append(annoItem)
                            
                            MapConfig.shared.route = self.drawRout(first: ViewModel.shared.lastLocation, second: p)
                        }
                        
                    } else if content.cmd == "CMD", content.subCmd == "LAOS_POSITION" { // 车的位置（车在来的路上）
                        let content2 = try decoder.decode(WebSocketPositionResult.self, from: Data(str.utf8))
                        
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            let carPosition = content2.laosPoint
                            let p = CLLocationCoordinate2D(latitude: carPosition.latitude, longitude: carPosition.longitude)
                            CarOrder.shared.carPosition = p
                            CarOrder.shared.leftTime = "\(carPosition.leftTime)"
                            CarOrder.shared.carNo = "\(carPosition.chepai)"
                            CarOrder.shared.laosPoint = carPosition
                            
                            CarOrder.shared.save()
                            CarOrder.shared.save(info: carPosition)
                            MapConfig.shared.setCarPos(p, carId: content2.peopleId, state: self.orderState, direction: carPosition.course.toDouble(), speed: carPosition.speed)
                            MapConfig.shared.route = self.drawRout(first: ViewModel.shared.lastLocation, second: p)
                            
                            logger.info("websockets position received:\(content2)")
                        }
                    } else if content.cmd == "CMD", content.subCmd == "LAOS_KAISHI" { // 开始
                        let content2 = try decoder.decode(WebSocketStartResult.self, from: Data(str.utf8))
                        
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                if let driver = content2.driver {
//                                    logger.info("driver:\(driver)")
//                                    let p = CLLocationCoordinate2D(latitude: driver.carLat!, longitude: driver.carLon!)
//                                    CarOrder.shared.carPosition = p
//
//                                    logger.info("currentState:\(self?.orderState ?? EnumCurrentState.none)")
//                                    if self?.orderState == .waiting {
                                    self.orderState = .running
//                                    }
//                                    MapConfig.shared.setCarPos(p, carId: content2.peopleId!, state: self!.orderState, direction: -1, speed: 0)
//                                    MapConfig.shared.route = self!.drawRout(first: ViewModel.shared.lastLocation, second: p)
//                                }
                            
                            logger.info("websockets position received:\(content2)")
                        }
                    } else if content.cmd == "CMD", content.subCmd == "LAOS_JIESHU" { // 结束
                        let content2 = try decoder.decode(WebSocketJieshuResult.self, from: Data(str.utf8))
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            
                            self.orderState = .paying
                            
                            CarOrder.shared.startPos
                            
                            let newOrder = TaxiOrder(context: DataManager.shared.persistentContainer.viewContext)
                            newOrder.endTime = Date().toStandardString
                            newOrder.startTime = Date(timeIntervalSince1970: TimeInterval(CarOrder.shared.startTime)).toStandardString
                            newOrder.distance = NSDecimalNumber(value: content2.mydistance)
                            newOrder.carNo = CarOrder.shared.carNo
                            newOrder.price = NSDecimalNumber(value: content2.price)
                            newOrder.orderNo = "\(content2.detectionID)"
                            DataManager.shared.addOrder(order: newOrder)
                            
                            MapConfig.shared.annotationItems.removeAll()
                            MapConfig.shared.route = nil
                            MapConfig.shared.followMode = false
                            MapConfig.shared.changed = true
                            let loc = ViewModel.shared.lastLocation
                            MapConfig.shared.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: loc.latitude, longitude: loc.longitude), span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
                        }
                    } else if content.cmd == "CMD" && (content.subCmd == "LAOS_PAYED" || content.subCmd == "LAOS_DRIVER_DESTROY_ORDER") { // 已支付
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            self.vm.isShowSuccessView = true
                            self.orderState = .payed
                        }
                    } else if content.cmd == "CMD" && content.subCmd == "LAOS_CAR_ARRIVED" { // 车到了
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            self.sendLocalNotification(message: NSLocalizedString("车已到达", comment: "The car had arrived"))
                        }
                    }  else {
                        DispatchQueue.main.async {
                            logger.info("[socket message] websockets received:\(content)")
                        }
                    }
                }
            }catch {
                self.logger.info("websockets error is \(error.localizedDescription)")
            }
            
        }

        connect()
//        // 5秒后断开连接
//        DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
//            wsManager.disconnect(reason: "测试完成")
//        }
    }
    
    
    
    func connect(){
        // 连接WebSocket
        wsManager.connect()
        
    }

    func reconnect() {
//        if isReconnecting { return }
//        isReconnecting = true
//
//        logger.info("开始重连 WebSocket")
//        stopReconnectTimer()
//
//        // 优化3：重连延迟，避免频繁重连
//        reconnectTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { [weak self] _ in
//            guard let self = self else {
//                print("self 被释放了，无法执行重连")
//                return
//            }
//           self.connect()
//           self.isReconnecting = false
//        }
//        logger.info("WebSocket 重连成功，状态: \(webSocketTask?.state ?? .completed)")
    }
    
    // 检查连接是否活跃
//    var isConnected: Bool {
//        return webSocketTask?.state == .running
//    }
    
    
    
//    func joinOpenId() {
//        var openId = ViewModel.shared.passenger.openId
//        if openId == "" {
//            openId = Singleton.shared.openId
//        }
//        if openId != "" {
//            join(ViewModel.shared.passenger.openId)
//        }
//        // TODO: fix
//    }
    
//    func stop() {
//        stopReconnectTimer()
//
//        webSocketTask?.cancel(with: .goingAway, reason: nil)
//        webSocketTask = nil
//        opened = false
//        isReconnecting = false
//        logger.info("WebSocket 连接已停止")
//    }
    
//    private func stopReconnectTimer() {
//       reconnectTimer?.invalidate()
//       reconnectTimer = nil
//   }
    
    func sendLocalNotification(message: String) {
        if appInBackground {
            handleIncomingMessage(message: message)
        }
    }
    
    // 接收到WebSocket消息后
    func handleIncomingMessage(message: String) {
        let content = UNMutableNotificationContent()
        content.title = "New Message"
        content.body = message
        content.sound = UNNotificationSound.default
        
        let request = UNNotificationRequest(identifier: "messageNotification", content: content, trigger: nil)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }
    
    func drawRout(first: CLLocationCoordinate2D, second: CLLocationCoordinate2D) -> MKPolyline {
        logger.info("drawRout: from \(first) to \(second)")
        var points = [CLLocationCoordinate2D]()
        points.append(first)
        points.append(second)
        return MKPolyline(coordinates: points, count: 2)
    }
    
//    private func receiveMessage() {
//        webSocketTask?.receive(completionHandler: { [weak self] result in
//            let logger = Logger(label: "websocket")
//            logger.info("\n========== websocket income message begin =============")
//            switch result {
//            case .failure(let error):
//                logger.error("接收消息失败: \(error)")
//                let code = (error as NSError).code
//                logger.info("错误码: \(code)")
//                self?.handleError(error)  // 统一错误处理
//            case .success(.string(let str)):
//                do {
//                    logger.info("[socket message] original:\n\(str)")
//                    let decoder = JSONDecoder()
//                    let contentBase = try decoder.decode(APIResponse.self, from: Data(str.utf8))
//                    if contentBase.cmd == "MESSAGE" {
//                        print("[socket message] MESSAGE")
//                        let contentMessage = try decoder.decode(WebSocketMessageBaseResult.self, from: Data(str.utf8))
//                        let openId = ViewModel.shared.passenger.openId
//                        if contentMessage.type == "text" {
//                            print("[socket message] MESSAGE text")
//                            let contentMessageText = try decoder.decode(WebSocketMessageTextResult.self, from: Data(str.utf8))
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                for m in contentMessageText.contents {
//                                    if m.type == "text" {
//                                        var textContent  = contentMessageText.content
//                                        if  let shortMessageCode = contentMessageText.phraseCode  {
//                                            if !shortMessageCode.isEmpty && shortMessageCode != "null" {
//                                                print("[Socket] [Message] [Phrase] code: \(shortMessageCode)")
//                                                textContent = self!.vm.getShortMessageContent(code: shortMessageCode)
//                                            }
//                                        }
//                                        
//                                        let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageText.from, name: "司机", openId: contentMessageText.from!, type: .Driver), text: textContent, type: .text, voice: nil, video: nil, url: nil, phraseCode: "")
//                                        logger.info("[socket message] text:\(message)")
//                                        
//                                        if contentMessageText.from != openId { // 自己发的消息
//                                            logger.info("[socket message] text append to array :\(message)")
//                                            CarOrder.shared.messages.append(message)
//                                            print("=--------====----------\(message)")
//                                            self!.sendLocalNotification(message: contentMessageText.content!)
//                                        }
//                                        
//                                    }
//                                }
//                                CarOrder.shared.save()
//                                print("[socket message] messages :\(CarOrder.shared.messages.count) ")
//                                if CarOrder.shared.messages.count > 0 && !ViewModel.shared.inChat {
//                                    print("[socket message] send .newMessage notice.")
//                                    let notice = Notification(name: .newMessage, object: nil, userInfo: nil)
//                                    NotificationCenter.default.post(notice)
//                                    
//                                }
//                            }
//                        } else if contentMessage.type == "image" {
//                            let contentMessageImage = try decoder.decode(WebSocketMessageMediaResult.self, from: Data(str.utf8))
//                            
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                for m in contentMessageImage.contents {
//                                    if m.type == "image" {
//                                        let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageImage.from, name: "司机", openId: contentMessageImage.from!, type: .Driver), text: nil, type: .image, voice: nil, video: nil, url: m.url, phraseCode: "")
//                                        //if !self!.appInBackground {
//                                        if contentMessageImage.from != openId { // 自己发的消息
//                                            logger.info("[socket message] image:\(message)")
//                                            CarOrder.shared.messages.append(message)
//                                            self!.sendLocalNotification(message: NSLocalizedString("收到一条图片消息", comment: "Received a picture message"))
//                                        }
//                                    }
//                                }
//                                if contentMessageImage.from != openId { // 自己发的消息
//                                    CarOrder.shared.save()
//                                }
//                                print("[socket message] messages :\(CarOrder.shared.messages.count) ")
//                                if CarOrder.shared.messages.count > 0 && !ViewModel.shared.inChat {
//                                    print("[socket message] send .newMessage notice.")
//                                    let notice = Notification(name: .newMessage, object: nil, userInfo: nil)
//                                    NotificationCenter.default.post(notice)
//                                    
//                                }
//                            }
//                        } else if contentMessage.type == "voice" {
//                            let contentMessageImage = try decoder.decode(WebSocketMessageMediaResult.self, from: Data(str.utf8))
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                for m in contentMessageImage.contents {
//                                    if m.type == "voice" {
//                                        let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageImage.from, name: "司机", openId: contentMessageImage.from!, type: .Driver), text: nil, type: .voice, voice: nil, video: nil, url: m.url, phraseCode: "")
//                                        if contentMessageImage.from != openId { // 自己发的消息
//                                            logger.info("[socket message] voice:\(message)")
//                                            CarOrder.shared.messages.append(message)
//                                            //}
//                                            self!.sendLocalNotification(message: NSLocalizedString("收到一条声音消息", comment: "Received a voice message"))
//                                        }
//                                    }
//                                }
//                                if contentMessageImage.from != openId { // 自己发的消息
//                                    CarOrder.shared.save()
//                                }
//                                print("[socket message] messages :\(CarOrder.shared.messages.count) ")
//                                if CarOrder.shared.messages.count > 0 && !ViewModel.shared.inChat {
//                                    print("[socket message] send .newMessage notice.")
//                                    let notice = Notification(name: .newMessage, object: nil, userInfo: nil)
//                                    NotificationCenter.default.post(notice)
//                                    
//                                }
//                            }
//                        }
//                    } else {
//                        let content = try decoder.decode(CMDResponse.self, from: Data(str.utf8))
//                        if content.cmd == "CMD", content.subCmd == "LAOS_JIEDAN" { // 接单
//                            let content2 = try decoder.decode(WebSocketJiedanResult.self, from: Data(str.utf8))
//                            
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                CarOrder.shared.driverId = content2.peopleId!
//                                CarOrder.shared.carNo = (content2.driver?.chepai)!
//                                CarOrder.shared.driverPhone = (content2.driver?.laosPhone)!
//                                if let headavitor = (content2.driver?.headavitor) {
//                                    CarOrder.shared.headavitor =  headavitor
//                                }
//                                let p = CLLocationCoordinate2D(latitude: (content2.driver?.carLat!)!, longitude: (content2.driver?.carLon!)!)
//                                
//                                CarOrder.shared.startTime = Date().secondsSince1970
//                                CarOrder.shared.carPosition = p
//                                
//                                logger.info("websockets jiedan received:\(content2)")
//                                
//                                self!.orderState = .waiting
//                                
//                                self!.sendLocalNotification(message: NSLocalizedString("司机已接单", comment: "The driver has accepted the ride."))
//                                
//                                MapConfig.shared.annotationItems.removeAll()
//                                let annoItem = MapAnnotationModel(coordinate: p, car: CarInfo(id: CarOrder.shared.driverId, carNo: CarOrder.shared.carNo, driverMobile: CarOrder.shared.driverPhone, direction: 0, speed: 0, status: .busy))
//                                MapConfig.shared.annotationItems.append(annoItem)
//                                
//                                MapConfig.shared.route = self!.drawRout(first: ViewModel.shared.lastLocation, second: p)
//                            }
//                            
//                        } else if content.cmd == "CMD", content.subCmd == "LAOS_POSITION" { // 车的位置（车在来的路上）
//                            let content2 = try decoder.decode(WebSocketPositionResult.self, from: Data(str.utf8))
//                            
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                let carPosition = content2.laosPoint
//                                let p = CLLocationCoordinate2D(latitude: carPosition.latitude, longitude: carPosition.longitude)
//                                CarOrder.shared.carPosition = p
//                                CarOrder.shared.leftTime = "\(carPosition.leftTime)"
//                                CarOrder.shared.carNo = "\(carPosition.chepai)"
//                                CarOrder.shared.laosPoint = carPosition
//                                
//                                CarOrder.shared.save()
//                                CarOrder.shared.save(info: carPosition)
//                                MapConfig.shared.setCarPos(p, carId: content2.peopleId, state: self!.orderState, direction: carPosition.course.toDouble(), speed: carPosition.speed)
//                                MapConfig.shared.route = self!.drawRout(first: ViewModel.shared.lastLocation, second: p)
//                                
//                                logger.info("websockets position received:\(content2)")
//                            }
//                        } else if content.cmd == "CMD", content.subCmd == "LAOS_KAISHI" { // 开始
//                            let content2 = try decoder.decode(WebSocketStartResult.self, from: Data(str.utf8))
//                            
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
////                                if let driver = content2.driver {
////                                    logger.info("driver:\(driver)")
////                                    let p = CLLocationCoordinate2D(latitude: driver.carLat!, longitude: driver.carLon!)
////                                    CarOrder.shared.carPosition = p
////
////                                    logger.info("currentState:\(self?.orderState ?? EnumCurrentState.none)")
////                                    if self?.orderState == .waiting {
//                                        self?.orderState = .running
////                                    }
////                                    MapConfig.shared.setCarPos(p, carId: content2.peopleId!, state: self!.orderState, direction: -1, speed: 0)
////                                    MapConfig.shared.route = self!.drawRout(first: ViewModel.shared.lastLocation, second: p)
////                                }
//                                
//                                logger.info("websockets position received:\(content2)")
//                            }
//                        } else if content.cmd == "CMD", content.subCmd == "LAOS_JIESHU" { // 结束
//                            let content2 = try decoder.decode(WebSocketJieshuResult.self, from: Data(str.utf8))
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                self?.orderState = .paying
//                                
//                                CarOrder.shared.startPos
//                                
//                                let newOrder = TaxiOrder(context: DataManager.shared.persistentContainer.viewContext)
//                                newOrder.endTime = Date().toStandardString
//                                newOrder.startTime = Date(timeIntervalSince1970: TimeInterval(CarOrder.shared.startTime)).toStandardString
//                                newOrder.distance = NSDecimalNumber(value: content2.mydistance)
//                                newOrder.carNo = CarOrder.shared.carNo
//                                newOrder.price = NSDecimalNumber(value: content2.price)
//                                newOrder.orderNo = "\(content2.detectionID)"
//                                DataManager.shared.addOrder(order: newOrder)
//                                
//                                MapConfig.shared.annotationItems.removeAll()
//                                MapConfig.shared.route = nil
//                                MapConfig.shared.followMode = false
//                                MapConfig.shared.changed = true
//                                let loc = ViewModel.shared.lastLocation
//                                MapConfig.shared.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: loc.latitude, longitude: loc.longitude), span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
//                            }
//                        } else if content.cmd == "CMD" && (content.subCmd == "LAOS_PAYED" || content.subCmd == "LAOS_DRIVER_DESTROY_ORDER") { // 已支付
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                self?.vm.isShowSuccessView = true
//                                self?.orderState = .payed
//                            }
//                        } else if content.cmd == "CMD" && content.subCmd == "LAOS_CAR_ARRIVED" { // 车到了
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                self!.sendLocalNotification(message: NSLocalizedString("车已到达", comment: "The car had arrived"))
//                            }
//                        }  else {
//                            DispatchQueue.main.async {
//                                logger.info("[socket message] websockets received:\(content)")
//                            }
//                        }
//                    }
//                } catch {
//                    logger.info("websockets error is \(error.localizedDescription)")
//                }
//                self?.receiveMessage()
//                
//            default:
//                logger.info("default")
//            }
//            logger.info("========== websocket income message end =============\n")
//        })
//    }
    
    // 统一错误处理
//        func handleError(_ error: Error) {
//            logger.error("WebSocket 错误: \(error.localizedDescription)")
//            
//            // 优化5：全面的错误处理和重连策略
//            if let urlError = error as? URLError {
//                switch urlError.code {
//                case .notConnectedToInternet, .networkConnectionLost:
//                    logger.info("网络连接丢失，准备重连")
//                    reconnect()
//                case .timedOut:
//                    logger.warning("请求超时，触发重连")
//                    reconnect()
//                default:
//                    logger.warning("其他网络错误，触发重连")
//                    reconnect()
//                }
//            } else {
//                logger.warning("非网络错误，触发重连")
//                reconnect()
//            }
//        }
    
//    func sendPing() {
//        webSocketTask?.sendPing { error in
//            let logger = Logger(label: "websocket")
//            if let error = error {
//                logger.info("Sending PING failed: \(error)")
//                if self.webSocketTask?.state == URLSessionTask.State.running {
//                    return;
//                }
////                // 取消当前连接
////                self.webSocketTask?.cancel(with: .goingAway, reason: nil)
//                DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
//                    // 开始重连
//                    self.reconnect()
//                }
//            }
//            
//            DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
//                self.sendPing()
//            }
//        }
//    }
    
//    // 加入 Join
//    private func join(_ openId: String) {
//        guard isConnected else {
//                   logger.warning("WebSocket 未连接，尝试重连")
//                   reconnect()
//                   return
//               }
//        logger.info("websocket-join")
//        let sendData = """
//         {
//           "cmd":"JOIN",
//           "peopleId":"\(openId)"
//         }
//      """
//        logger.info("send data: \(sendData)\n")
//        webSocketTask?.send(.string(sendData), completionHandler: { error in
//            let logger = Logger(label: "websocket")
//            if let error = error {
//                logger.info("join send error : \(error.localizedDescription)")
//            }
//            
//        })
//    }
    
    
     func sendJoinMessage(){
         var openId = ViewModel.shared.passenger.openId
         if openId != "" {
             let sendData = """
              {
                "cmd":"JOIN",
                "peopleId":"\(openId)"
              }
           """
             wsManager.sendMessage(sendData) { error in
                 if let error = error {
                     print("❌ 发送测试消息失败: \(error.localizedDescription)")
                 } else {
                     print("✅ 测试消息发送成功1")
                     //                     DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                     //                         ViewModel.shared.driverInfo.online = true
                     //                         if !LocationManager.shared.hasSetRegion {
                     //                             self.sendDriverPosition(runningOrder: ViewModel.shared.runningFeeOrder, pos: ViewModel.shared.lastLocation)
                     //                            LocationManager.shared.hasSetRegion = true
                     //                         }
                     //                     }
                     
                 }
             }
         }
     }
    
    
    
    // 心跳 Heart
//    func live() {
//        guard isConnected else {
//                   logger.warning("WebSocket 未连接，尝试重连")
//                   reconnect()
//                   return
//               }
//        
//        let openId = ViewModel.shared.passenger.openId
//        logger.info("websocket-heart")
//        let sendData = """
//         {
//           "cmd":"ONHEART",
//           "peopleId":"\(openId)"
//         }
//      """
//        logger.info("send data: \(sendData)\n")
//        // logger.info(Unmanaged.passUnretained(self).toOpaque())
//        webSocketTask?.send(.string(sendData), completionHandler: { error in
//            let logger = Logger(label: "websocket")
//            if let error = error {
//                logger.info("heart send error : \(error.localizedDescription)")
//            }
//            
//        })
//    }
    
    // MARK: 叫车 callCar
    
    func callCar(callInfo: [DataCall], orderId: String, driverId: String,completion: @escaping () -> Void) {
        let logger = Logger(label: "websocket")
        let openId = ViewModel.shared.passenger.openId
        logger.info("websocket-callcar")
        do {
            let jsonData = try JSONEncoder().encode(callInfo)
            let jsonString = String(data: jsonData, encoding: .utf8)!
            
            let sendData = """
         {"cmd":"LAOS_CALLCAR","peopleId":"\(openId)","detectionId":0,"detections":\(jsonString)}
         """
            logger.info("send data: \(sendData)\n")
            wsManager.sendMessage(sendData) { error in
                if let error = error {
                    print("❌ 发送测试消息失败: \(error.localizedDescription)")
                } else {
                    print("✅ 测试消息发送成功6")
                    completion()
                }
            }
            
        } catch {
            logger.info("call car exception:\(error.localizedDescription)")
        }
    }
    
    // MARK: 撤销叫车
    
    func cancelOrder(orderId: String) {
        let logger = Logger(label: "websocket")
        let openId = ViewModel.shared.passenger.openId
        logger.info("websocket-cancelOrder")
        let sendData = """
      {"cmd":"CHEHUI","peopleId":"\(openId)","detectionId":\(orderId)}
      """
        logger.info("cancel order send data: \(sendData)\n")
        
        wsManager.sendMessage(sendData) { error in
            if let error = error {
                print("❌ 发送测试消息失败: \(error.localizedDescription)")
            } else {
                print("✅ 测试消息发送成功6")
            }
        }
    }
    
    // MARK: 发送客户端位置
    
    func sendPosition(orderId: String, driverId: String, pos: CLLocationCoordinate2D) {
        let logger = Logger(label: "websocket")
        let openId = ViewModel.shared.passenger.openId
        logger.info("websocket-sendPosition")
        let sendData = """
      {"cmd":"LAOS_CLIENT_POSITION",
      "peopleId":"\(openId)",
      "detectionId":\(orderId),
      "driver_openId":"\(driverId)",
      "laos_point": {
        "latitude":\(pos.latitude),
        "longitude":\(pos.longitude)
      }
      }
      """
        logger.info("client position send data: \(sendData)\n")
        wsManager.sendMessage(sendData) { error in
            if let error = error {
                print("❌ 发送测试消息失败: \(error.localizedDescription)")
            } else {
                print("✅ 测试消息发送成功2")
            }
        }
    }
    
    func sendTextMessage(driverId: String, orderId: String, content: String,phraseCode: String) {

        let logger = Logger(label: "websocket")
        let openId = ViewModel.shared.passenger.openId
        
        var sendData = """
        {"cmd":"MESSAGE",
        "content":"\(content)",
        "peopleId":"\(openId)",
        "roomId":"\(openId)-\(driverId)",
        "detectionId":\(orderId),
        "from":"\(openId)",
        "to":"\(driverId)",
        "avatar":"",
        "receiverJSON": [{
          "peopleId":"\(driverId)"
        }],
        "type":"text",
        "phrasecode":"\(phraseCode)"
        }
        """
        /*
         {"cmd":"MESSAGE",
         "content":"\(content)",
         "peopleId":"\(openId)",
         @@ -442,6 +472,7 @@ class WebSocketService: ObservableObject {
         "type":"text"
         }}
         */
//        logger.info("[websocket] client send message: \(sendData)\n")
        
        wsManager.sendMessage(sendData) { error in
            if let error = error {
                print("❌ 发送测试消息失败: \(error.localizedDescription)")
            } else {
                print("✅ 测试消息发送成功1")
                
            }
        }
    }
    
    func sendImageMessage(driverId: String, orderId: String, url: String) {
    
        let logger = Logger(label: "websocket")
        let openId = ViewModel.shared.passenger.openId
        
        let sendData = """
      {"cmd":"MESSAGE",
      "content":"",
      "url":"\(url)",
      "peopleId":"\(openId)",
      "roomId":"\(openId)-\(driverId)",
      "detectionId":\(orderId),
      "from":"\(openId)",
      "to":"\(driverId)",
      "avatar":"",
      "receiverJSON": [{
        "peopleId":"\(driverId)"
      }],
      "type":"image"
      }
      """
        logger.info("client send image message: \(sendData)\n")
        wsManager.sendMessage(sendData) { error in
            if let error = error {
                print("❌ 发送测试消息失败: \(error.localizedDescription)")
            } else {
                print("✅ 测试消息发送成功1")
                
            }
        }
    }
    
    func sendVoiceMessage(driverId: String, orderId: String, url: String) {

        let logger = Logger(label: "websocket")
        let openId = ViewModel.shared.passenger.openId
        
        let sendData = """
      {"cmd":"MESSAGE",
      "content":"",
      "url":"\(url)",
      "peopleId":"\(openId)",
      "roomId":"\(openId)-\(driverId)",
      "detectionId":\(orderId),
      "from":"\(openId)",
      "to":"\(driverId)",
      "avatar":"",
      "receiverJSON": [{
        "peopleId":"\(driverId)"
      }],
      "type":"voice"
      }
      """
        logger.info("client send image message: \(sendData)\n")
        // logger.info(Unmanaged.passUnretained(self).toOpaque())
        wsManager.sendMessage(sendData) { error in
            if let error = error {
                print("❌ 发送测试消息失败: \(error.localizedDescription)")
            } else {
                print("✅ 测试消息发送成功1")
                
            }
        }
    }
}
